﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinkCard.Model;

namespace LinkCard.Dao
{
    public class UserDao:ITopLinkDao
    {
        public int Add(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objAdd = (User)obj;
                db.AddToUsers(objAdd);
                rs = db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Update(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objUpdate = (User)obj;
                var id = objUpdate.UserID;
                var oldObj = db.Users.FirstOrDefault(t => t.UserID == id);
                if (oldObj != null)
                {
                    oldObj.Fullname = objUpdate.Fullname;
                    oldObj.Type = objUpdate.Type;
                    oldObj.Permission = objUpdate.Permission;
                    oldObj.Description = objUpdate.Description;
                    oldObj.MobilePhone = objUpdate.MobilePhone;
                    oldObj.Address = objUpdate.Address;
                    oldObj.Email = objUpdate.Email;
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Delete(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objDel = (User)obj;
                var id = objDel.UserID;
                var oldObj = db.Users.FirstOrDefault(t => t.UserID == id);
                if (oldObj != null)
                {
                    db.DeleteObject(oldObj);
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public User GetById(long id)
        {
            var ct = new User();
            try
            {
                var db = new TopLinkEntities();
                ct = db.Users.FirstOrDefault(t => t.UserID == id);
            }
            catch (Exception)
            {
                throw;
            }
            return ct;
        }

        public List<User> GetAll()
        {
            var lst = new List<User>();
            try
            {
                var db = new TopLinkEntities();
                lst = db.Users.ToList();
            }
            catch (Exception)
            {
                throw;
            }
            return lst;
        }
    }
}
